import {computed, defineComponent,onMounted,ref} from 'vue'
import RtAddPortletHelper from './RtAddPortletHelper.vue'
import RtEditorPortletHelper from './RtEditorPortletHelper.vue'
import FloatActionButton from './FloatActionButton.vue'
import useMappingProps from 't/common/hooks/useMappingProps';
import Portal from './Portal.vue'
import RtAddIndicatorPortletHelper from './RtAddIndicatorPortletHelper.vue'
import _ from 'lodash'
import {PortalInstcne} from './PortalInstcne'
export default defineComponent({
    name: 'TPortal',
    components: {
         RtAddPortletHelper,
         FloatActionButton,
         Portal,
         RtEditorPortletHelper,
         RtAddIndicatorPortletHelper
    },
    props: {
        pageCode:{
            type:String,
            default:'Page_101629'
        },
        pageID:{
            type:String,
            default:'0c90e801-44f3-49b7-87dc-d54d60ab2dbe'
        },
        instanceCode:String,
        localvars:Object,
        divContainerMinHeight:{
            default:'60px',
            type:String
        },
        visible:{
            default:true,
            type:Boolean
        },
        customEditEnable:{
            default:true,
            type:Boolean
        },
        isAutoRefresh:{
            default:false,
            type:Boolean
        },
        refreshInterval:{
            default:10000,
            type:[Number,String]
        },
        portalPadding:{
            default:'10',
            type:[String,Number]
        },
        portletBackgroundColor:{
            default:'#fff',
            type:String
        },
        eventList:Object,

        enablePlan:{
            default:()=>{
                return false
            },
            type:Boolean
        },
        verticalCompact:{
            default:()=>{
                return true
            },
            type:Boolean
        },
        preventCollision:{
            default:()=>{
                return false
            },
            type:Boolean
        },
        
    },
    emits: ['OnComplete','OnEvent_Filter','OnChange','OnPlanBeEdit'],
    setup(props, { emit,expose }) {
        const refRtAddPortletHelper= ref()
        const refPortal = ref(null)
        const refFloatActionButton = ref(null)
        const refRtEditorPortletHelper = ref(null)
        const refRtAddIndicatorPortletHelper = ref(null)
        let lastQueryId = ''
        const loadFInshed = ref(false)
        let UI_MetricsSet_Promise =  Funcs.LoadUmdComponent('UI_MetricsSet')
                let UI_CommonCondition_Promise = Funcs.LoadUmdComponent('UI_CommonCondition')
        Promise.all([UI_MetricsSet_Promise,UI_CommonCondition_Promise]).then(res=>{
            loadFInshed.value=true
        })
        const publicParamChanged = (data)=>{
            if(!data) return
            if(! window.LocalVars.PublicParams){
                window.LocalVars.PublicParams={}
            }
            for(let i in data){
                if(_.get(window.LocalVars.PublicParams,i)!=data[i]){
                    _.set(window.LocalVars.PublicParams,i,data[i])
                }
            }
        }
        const [mappingProps, mappingExpose] = useMappingProps(props,{
            PublicParamChanged:publicParamChanged,
            publicParamChanged:publicParamChanged,
            getCurrectInstance:()=>{
               
               let nstanceObject = _.cloneDeep(refPortal.value?.curInstance) 

               nstanceObject.PortletInstances = refPortal.value?.formatData(refPortal.value?.element.list)||nstanceObject.PortletInstances

               return _.cloneDeep(nstanceObject) 
            },
            setInstance(ins){
                refPortal.value?.setCurInstance(ins)
            },
            setInstanceId:(id)=>{
                if(lastQueryId==id) return
                lastQueryId=id
                if(!id){
                    let portalInstcne =  _.cloneDeep(PortalInstcne)
                    let instceCode =`fasr_legacy_portal_${Funcs.Guid().substring(30)}` 
                    portalInstcne.ID=''
                    portalInstcne.Code=instceCode
                    portalInstcne.PortalComponentCode=instceCode
                    portalInstcne.PortletInstances=[]
                    portalInstcne.LayOutInfos=[ {
                        "MultitierAdaptation": "md",
                        "LayOutInfo":'[]'
                    }]
                    portalInstcne.LayoutInfoResponsive={lg:{
                        "MultitierAdaptation": "lg",
                        "LayOutInfo":'[]'
                    },md:{
                        "MultitierAdaptation": "md",
                        "LayOutInfo":'[]'
                    },sm:{
                        "MultitierAdaptation": "sm",
                        "LayOutInfo":'[]'
                    },xs:{
                        "MultitierAdaptation": "xs",
                        "LayOutInfo":'[]'
                    },xxs:{
                        "MultitierAdaptation": "xxs",
                        "LayOutInfo":'[]'
                    }}
                    //refPortal.value?.setCurInstance(portalInstcne)
                    return new Promise((resolve)=>{
                        refPortal.value?.setCurInstance(portalInstcne)
                        resolve(1)
                    })
                }
                return new Promise((resolve)=>{
                    getPortalInstance(id).then(portalInstcne=>{
                        refPortal.value?.setCurInstance(portalInstcne)
                        resolve(1)
                    })
                })
                
                //根据id 请求当前方案内容
                //渲染
                //如果id不存在，新增方案
            },
            edit:()=>{
                refPortal.value&&(refPortal.value.isLock = false)
            },
            closeEdit:()=>{
                refPortal.value&&(refPortal.value.isLock = true)
                refFloatActionButton.value&&(refFloatActionButton.value.isOpen=false)
            },
            addPortlet:()=>{
                if(refPortal.value.isLock){
                    refPortal.value.isLock = false
                }
                refRtAddPortletHelper.value.open()
            },
            backup:()=>{
                refPortal.value&&(refPortal.value.backup())
            },
            rejestorAdvanceQueryComponent:(vm)=>{
                AdvanceQueryComponent.value=vm
            },
            saveLayoutChanged:()=>{
                refPortal.value&&(refPortal.value.saveLayoutChanged())
            },
            rejestorCallBack:()=>{
                refPortal.value&&(refPortal.value.rejestorCallBack())
            },
            savePortalPlanContent:(isSvae)=>{
                refPortal.value&&(refPortal.value.savePortalPlanContent(isSvae))
                
            }
        });
        const portalParamsInstance = ref([])
        const currenctInstanceCode = ref('')
        const portalInstance = ref(null)
        const reloadPortal = ref(false)
        
        const getPortalInstance = (id)=>{
            
            let sgUrl =`${window.FrameSGHost}FASR-GetPortalInstance&fasdevappid=${window.getFasDevAppId()}`;
            return new Promise((resolve, reject) => {
                if(!id) return {}
                // resolve(_.cloneDeep(PortalInstcne))
                // return
                window.getDataAsync(
                  sgUrl,
                  'post',
                  {
                    id: id,
                  },
                  result => {
                    
                    let temp = JSON.stringify([])
                    if(!result.data){
                        result.data = {
                            LayOutInfos:[]
                        }
                    }
                    if(!result.data.LayOutInfos||!result.data.LayOutInfos[0]||!result.data.LayOutInfos[0].LayOutInfo) {
                        result.data.LayOutInfos=[
                            {
                              "MultitierAdaptation": 'lg',
                              "LayOutInfo":temp
                            }
                          ]
                    }
                    if(!result.data.LayoutInfoResponsive||!result.data.LayoutInfoResponsive.lg) {
                        result.data.LayoutInfoResponsive={
                            "lg": {
                                "MultitierAdaptation": 'lg',
                                "LayOutInfo": temp
                              },
                            "md": {
                                "MultitierAdaptation": 'md',
                                "LayOutInfo": temp
                              },
                            "sm": {
                                "MultitierAdaptation": 'sm',
                                "LayOutInfo":temp
                              },
                            "xs": {
                                "MultitierAdaptation": 'xs',
                                "LayOutInfo": temp
                              },
                            "xxs": {
                                "MultitierAdaptation": 'xxs',
                                "LayOutInfo": temp
                              }
                        }
                    }
                    resolve(result.data);
                  },
                  error => {
                    reject(error);
                  },
                );
              });
        }
        //FASR-GetPortalInstance
        const showChangePortal = computed(()=>{
            if(refPortal.value){
                let customList = refPortal.value.curInstanceList.filter(
                    item => item.InstanceType == 1,
                  );
                  let persionInstanceList = refPortal.value.curInstanceList.filter(
                    item => item.InstanceType == 2,
                  );
                return refPortal.value.isMaster&&refPortal.value.portalSelectList.length&&(customList.length!=0||persionInstanceList.length!=0)
            }
            return false
        })
        const portalType = computed(()=>{
            if(refPortal.value){
                return refPortal.value.portalSelectList.filter(item=>refPortal.value.curInstance&&item.ID==refPortal.value.curInstance.ID)[0]
            }
            return false
        })
        const personList =ref(null)
        
        const customList =ref(null)
        
        const proxyCurInstance = ref(null)
        const AdvanceQueryComponent= ref('')
        expose(mappingExpose)
        return ()=>{
            if(!mappingProps.visible){
                return ''
            }
            return(
                <div>
                    {(()=>{
                        if(!reloadPortal.value){
                            return <Portal preventCollision={mappingProps.preventCollision} verticalCompact={mappingProps.verticalCompact} enablePlan={mappingProps.enablePlan} eventList={props.eventList}  PageID={mappingProps.pageID} ref={refPortal} display={{}} InstanceCode={mappingProps.instanceCode} 
                            AdvanceQueryComponent={AdvanceQueryComponent.value}
                            onComplete={(e)=>{ 
                                emit('OnComplete')
                             }}
                             onChange={(e)=>{
                                let nstanceObject = _.cloneDeep(refPortal.value?.curInstance) 
                                nstanceObject.PortletInstances = refPortal.value?.formatData(refPortal.value?.element.list)||nstanceObject.PortletInstances
                                if(AdvanceQueryComponent.value){
                                    AdvanceQueryComponent.value.PortalChanged(true)
                                }
                                emit('OnChange',nstanceObject)
                             }}
                             onPlanBeEdit={(e)=>{

                                emit('OnPlanBeEdit')
                             }}
                            onReloadPortal={(e)=>{
                                if(e&&e.clear){
                                    proxyCurInstance.value=null
                                }
                                reloadPortal.value=true
                                setTimeout(() => {
                                    reloadPortal.value=false
                                }, 200);
                            }}
                            onEvent_Filter={(Event_Filter_Content)=>{
                                if(!Event_Filter_Content) return

                                emit(`${Event_Filter_Content.portalCode}_${Event_Filter_Content.eventName}`,Event_Filter_Content.data,Event_Filter_Content)

                                //emit('Event_Filter',Event_Filter_Content.portalCode,Event_Filter_Content.data)

                            }}
                            divContainerMinHeight={mappingProps.divContainerMinHeight}
                            portalPadding={mappingProps.portalPadding}
                            onEditData={(e)=>{
                                portalParamsInstance.value = e.portalParamsInstance
                                currenctInstanceCode.value = e.currenctInstanceCode
                                portalInstance.value = e.data
                                refRtEditorPortletHelper.value.open()
                            }}
                            isAutoRefresh={mappingProps.isAutoRefresh}
                            refreshInterval={mappingProps.refreshInterval}
                            portletBackgroundColor={mappingProps.portletBackgroundColor}
                            localvars={mappingProps.localvars}
                            proxyCurInstance={proxyCurInstance.value}
                            ></Portal>
                        }
                    })()}
                    {(()=>{
                        if(mappingProps.customEditEnable){
                            return  <FloatActionButton
                            enablePlan={mappingProps.enablePlan}
                            personList={personList.value}
                            isMaster={  refPortal.value&&refPortal.value.isMaster}
                            customList={customList.value}
                            portalType={portalType.value}
                            showChangePortal={showChangePortal.value}
                            ref={refFloatActionButton}
                            onChangeStatus={(e)=>{
                                refPortal.value&&(refPortal.value.isLock = !e)
                            }}
                            onOperate={(e)=>{
                                switch(e.type){
                                    case 'add':
                                       
                                        if(!refRtAddPortletHelper.value){
                                            setTimeout(() => {
                                                refRtAddPortletHelper.value&&refRtAddPortletHelper.value.open()
                                                refFloatActionButton.value&&(refFloatActionButton.value.isOpen=true)
                                                refPortal.value&&(refPortal.value.isLock = false)
                                            }, 1000);
                                        }else{
                                            refRtAddPortletHelper.value&&refRtAddPortletHelper.value.open()
                                            refFloatActionButton.value&&(refFloatActionButton.value.isOpen=true)
                                            refPortal.value&&(refPortal.value.isLock = false)
                                        }
                                        break
                                    case 'add1':
                                        refRtAddIndicatorPortletHelper.value.open()
                                        refFloatActionButton.value&&(refFloatActionButton.value.isOpen=true)
                                        refPortal.value&&(refPortal.value.isLock = false)
                                        break
                                    case 'resetPlan':
                                        refPortal.value&&(refPortal.value.backup())
                                        refFloatActionButton.value&&(refFloatActionButton.value.isOpen=false)
                                        refPortal.value&&(refPortal.value.isLock = true)
                                        AdvanceQueryComponent.value.PortalChanged(false)
                                        break
                                    case 'restoreDefault':
                                        if(refPortal.value){
                                            refPortal.value.curInstance.InstanceType==2&&(refPortal.value.deletePersonPortal())
                                            refPortal.value.curInstance.InstanceType==1&&(refPortal.value.deleteCurrentPortal())
                                        }
                                        // refPortal.value&&(refPortal.value.deletePersonPortal())
                                        refFloatActionButton.value&&(refFloatActionButton.value.isOpen=false)
                                        refPortal.value&&(refPortal.value.isLock = true)
                                        break
                                    case 'save':
                                        refPortal.value&&(refPortal.value.saveLayoutChanged())
                                        refFloatActionButton.value&&(refFloatActionButton.value.isOpen=false)
                                        refPortal.value&&(refPortal.value.isLock = true)
                                        break
                                    case 'changeCurInstance':
                                        // if(refPortal.value.canChange){
                                        //     return
                                        // }
                                        customList.value= refPortal.value.curInstanceList.filter(item=>item.InstanceType==1)[0]
                                         personList.value =  refPortal.value.curInstanceList.filter(item=>item.InstanceType==2)[0]
                           
                                        proxyCurInstance.value=  refPortal.value.curInstanceList.filter(item=>item.ID!=e.value)[0]
                                        let id = refPortal.value.portalSelectList.filter(item=>item.ID!=e.value)[0].ID
                                        refPortal.value&&(refPortal.value.curInstanceSelectChange(id))
                                        reloadPortal.value=true
                                        setTimeout(() => {
                                            reloadPortal.value=false
                                        }, 50);
                                        // refFloatActionButton.value&&(refFloatActionButton.value.isOpen=true)
                                        // setTimeout(() => {
                                        //     refPortal.value&&(refPortal.value.isLock = false)
                                        // }, 30);
                                        // setTimeout(() => {
                                        //     refPortal.value&&(refPortal.value.isLock = false)
                                        // }, 50);
                                        // setTimeout(() => {
                                        //     refPortal.value&&(refPortal.value.isLock = false)
                                        // }, 80);
                                        break
                                }
                               
                            }}/>
                        }
                    })()}
                   {(()=>{
                        if(loadFInshed.value){
                            return  <RtAddPortletHelper ref={refRtAddPortletHelper}  onSureData={(e)=>{
                                refPortal.value&&(refPortal.value.addPortletSureData(e)) 
                            }}
                            />
                        }
                   })()}
                   
                   
                   
                      <RtAddIndicatorPortletHelper ref={refRtAddIndicatorPortletHelper}  onSureData={(e)=>{
                        refPortal.value&&(refPortal.value.addPortletSureData(e)) 
                    }}
                   
                    />
                   
                   {(()=>{
                        if(loadFInshed.value){
                            return   <RtEditorPortletHelper portalInstance={portalInstance.value}  portalParamsInstance={portalParamsInstance.value} currenctInstanceCode={currenctInstanceCode.value} ref={refRtEditorPortletHelper}
                            onSureData={(e)=>{
                                refPortal.value&&(refPortal.value.updatePortletSureData( _.cloneDeep(e))) 
                            }}
                            localvars={mappingProps.localvars}
                            ></RtEditorPortletHelper>
                        }
                   })()}
                   
                </div>
            )
        } 
    },
})